import json

def load_data_from_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)
        return data
    except FileNotFoundError:
        print(f"错误: 文件 {file_path} 未找到。")
        return None
    except json.JSONDecodeError:
        print(f"错误: 文件 {file_path} 不是有效的 JSON 文件。")
        return None

def find_turning_points(data, min_decline_days=3):
    stock_prices = {}
    all_dates = sorted({day["trandt"] for day in data}, reverse=True)

    # 获取最大日期
    max_date = all_dates[0]

    # 组织数据，以股票代码为键，存储每个日期的收盘价
    for day in data:
        date = day["trandt"]
        for stock in day["data"]["diff"]:
            stock_code = stock["f12"]
            close_price = stock["f2"]

            if stock_code not in stock_prices:
                stock_prices[stock_code] = {}

            stock_prices[stock_code][date] = close_price

    # 找出在最大日期的拐点数据
    turning_points = []
    for stock_code, prices in stock_prices.items():
        # 确保最大日期和前几天的数据都存在
        if max_date not in prices:
            continue

        # 获取最大日期的前几个交易日
        previous_dates = [date for date in all_dates if date < max_date][:min_decline_days]

        # 确保前几个交易日的数据都存在
        if len(previous_dates) < min_decline_days or any(date not in prices for date in previous_dates):
            continue

        # 确认前几天的价格是连续下降的
        is_declining = all(prices[previous_dates[i]] < prices[previous_dates[i + 1]] for i in range(len(previous_dates) - 1))

        # 确认最大日期的价格比前一天高
        if is_declining and prices[max_date] > prices[previous_dates[0]]:
            turning_points.append({
                "stock_code": stock_code,
                "date": max_date,
                "price": prices[max_date],
                "decline_days": len(previous_dates)
            })

    return turning_points

def print_turning_points(turning_points):
    print("拐点数据:")
    for point in turning_points:
        print(f"股票代码: {point['stock_code']}")
        print(f"日期: {point['date']}")
        print(f"价格: {point['price']}")
        print(f"连续下跌天数: {point['decline_days']}")
        print()

# 主程序执行
file_path = '/Users/macbookair/workspace/pythonlearning/01test/tiantianjijin/all_processed_data.json'
data = load_data_from_file(file_path)

if data:
    turning_points = find_turning_points(data)
    print_turning_points(turning_points)
else:
    print("没有可处理的数据。")
